package com.edu.atams.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.atams.common.lang.Result;
import com.edu.atams.entity.ClassSubject;
import com.edu.atams.entity.Subject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@RestController
@RequestMapping("/subject")
public class SubjectController extends BaseController {
    @GetMapping("/list")
    public Result list(String name){
        Page page = subjectService.page(getPage(), new QueryWrapper<Subject>().like(StrUtil.isNotBlank(name), "name", name));
        return Result.succ(page);
    }

    @PostMapping("/save")
    @Transactional
    public Result save(@RequestBody Subject subject){
        List<Subject> subjectList = subjectService.list(new QueryWrapper<Subject>().in("name", subject.getName()));
        if (subjectList.size() > 0){
            return Result.fail("名称重复了");
        }else {
            subjectService.save(subject);
            return Result.succ("");
        }

    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody Subject subject){
        subjectService.updateById(subject);
        return Result.succ("");
    }

    @PostMapping("/remove")
    @Transactional
    public Result remove(@RequestBody Integer[] ids){
        List<ClassSubject> classSubjectList = classSubjectService.list(new QueryWrapper<ClassSubject>().in("subject_id", Arrays.asList(ids)));
        if (classSubjectList.size() > 0){
            return Result.fail("请先删除相关的任课信息！");
        }else {
            subjectService.removeByIds(Arrays.asList(ids));
            return Result.succ("");
        }

    }
}
